package air2.totc.common;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import air2.totc.R;
import air2.totc.crypt.AESEncoder;
import air2.totc.crypt.DESEncoder;
import air2.totc.crypt.TripleDesEncoder;
import air2.totc.messaging.GestionSMS;
import air2.totc.messaging.Message;
import air2.totc.testing.*;
public class decoderSMS extends Activity {
	private Button decoderSMS,effacerBDD;
	 GestionSMS gestionnaireSMS;
	 EditText decodeArea,cle;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.decodemessage);
        decoderSMS = (Button) findViewById(R.id.totcDecode);
        decoderSMS.setOnClickListener(new View.OnClickListener() {		
			public void onClick(View v) {
				  cle = (EditText) findViewById(R.id.cleDecodage);
				  decodeArea = (EditText) findViewById(R.id.decodeArea);
				  Spinner spinner = (Spinner) findViewById(R.id.listeMessages);
				  String id =spinner.getSelectedItem().toString();
				  String[] tmp = id.split(" : ");
				  
				 gestionnaireSMS = new GestionSMS(v.getContext());
				 gestionnaireSMS.open();
				 int typeCrypto = gestionnaireSMS.selectTypeCryptoFromID(Integer.parseInt(tmp[0]));  
				 gestionnaireSMS.close();
				  Toast.makeText(v.getContext(),"test decode passphrase="+cle.getText().toString().getBytes()+"cle="+cle.getText().toString()+" message="+decodeArea.getText().toString(),Toast.LENGTH_LONG).show();
				  try{
					  String var="";
					  switch(typeCrypto){
					  case 1:
							DESEncoder enc = new DESEncoder(cle.getText().toString().getBytes());
							var = enc.decode(decodeArea.getText().toString());
						  break;
					  case 2 :
						  TripleDesEncoder tdesEnc = new TripleDesEncoder(cle.getText().toString().getBytes());
						  var = tdesEnc.decode(decodeArea.getText().toString());
						  break;
					  case 3 :
						  AESEncoder aesEnc = new AESEncoder(cle.getText().toString().getBytes());
						  var = aesEnc.decode(decodeArea.getText().toString());
						  break;
					  }
					  decodeArea.setText(var);
				  }
				  catch(Exception e){
					  Toast.makeText(v.getContext(),"erreur de decodage",Toast.LENGTH_LONG).show();
				  }

			}
        }); 
        effacerBDD = (Button) findViewById(R.id.effacerBDD);
        effacerBDD.setOnClickListener(new View.OnClickListener() {	
			public void onClick(View v) {
				  gestionnaireSMS = new GestionSMS(v.getContext());
				  gestionnaireSMS.erase();
			}
        }); 
        decodeArea = (EditText)findViewById(R.id.decodeArea);
		 gestionnaireSMS = new GestionSMS(this);
		 ArrayList<String> idPhone = new ArrayList<String>();
		 //ArrayList<Message> smsList = new  ArrayList<Message>();
		
		 gestionnaireSMS.open();
		 ArrayList<Message> smsList = (ArrayList<Message>) gestionnaireSMS.getAllSMS();  
		 gestionnaireSMS.close();
		
		 Message mess;
		 Iterator<Message> it = smsList.iterator();
		 
		 while(it.hasNext())
		 {
			 mess = it.next();
			 
			// idPhone.add(""+mess.getId_sms()+" : "+getContactNameByID(getContactIDByPhone("0"+mess.getId_contact())));
			 idPhone.add(""+mess.getId_sms()+" : 0"+mess.getId_contact());
		 }
		 String[] textSpinner = new String[idPhone.size()];
		 for(int i=0;i<idPhone.size();i++){
			 textSpinner[i]=idPhone.get(i);
		 }
	    Spinner spinner = (Spinner) findViewById(R.id.listeMessages);
	    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,textSpinner);
        spinner.setAdapter(spinnerArrayAdapter);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
					String[] tmp=parentView.getItemAtPosition(position).toString().split(" : ");
					
					 gestionnaireSMS.open();
					 decodeArea.setText(gestionnaireSMS.selectMessageFromID(Integer.parseInt(tmp[0])));
					 gestionnaireSMS.close();
					
			}
			public void onNothingSelected(AdapterView<?> arg0) {
				// rien
			}
        });

	    Toast.makeText(this,"tout va bien",Toast.LENGTH_LONG).show();
    }
    public String getContactNameByID(String idContact){
    	String name = "Anonyme";
    	long id =0;
    	try{
    		id= Long.parseLong(idContact);
    	}catch(Exception e){
    		
    	}
    	if(id!=0){
	    	 Cursor cursor = null;  
	         // requéte pour récupérer le numéro du téléphone
	         cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,  
	                 null, ContactsContract.Contacts._ID + "=?", new String[] { idContact },  
	                 null);  
	
	         int phoneIndex = cursor.getColumnIndex(Phone._ID);  
	
	         // on récupére le premier numéro de téléphone
	         if (cursor.moveToFirst()) {  
	        	 name = cursor.getString(phoneIndex);  
	         }
	         cursor.close();  
    	}
    	return name;
    }
	public String getContactIDByPhone(String phoneNumber){
        Cursor cursor = null;  
        String phoneID="0";
        // requéte pour récupérer le numéro du téléphone
        cursor = getContentResolver().query(Phone.CONTENT_URI,  
                null, Phone.DATA + "='?'", new String[] { phoneNumber },  
                null);  

        int phoneIndex = cursor.getColumnIndex(Phone._ID);  

        // on récupére le premier numéro de téléphone
        if (cursor.moveToFirst()) {  
        	phoneID = cursor.getString(phoneIndex);  
        }
        cursor.close();  
        return phoneID;
	}
	

}
